package org.lsj.kit.config;

import org.lsj.kit.mapper.MenuResourceMapper;
import org.lsj.kit.mapper.RoleMapper;
import org.lsj.kit.model.MenuResource;
import org.lsj.kit.model.Role;
import org.springframework.security.access.*;
import org.springframework.security.access.SecurityConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 豆腐干Sama on 2019/3/5.
 */
public class ConfigAttributeCache {
    public static Map<String,List<ConfigAttribute>> configCacheMap=new HashMap<>();

    public static void refreshCache(MenuResourceMapper resourceMapper, RoleMapper roleMapper) {
        List<MenuResource> menuResources = resourceMapper.selectByExample(null);
        menuResources.forEach(resource-> {
            String url = resource.getUrl();
            System.out.println(url);
            List<Role> roles = roleMapper.queryByResourceUrl(url);
            List<ConfigAttribute> configAttribute = getConfigAttribute(roles);
            configCacheMap.put(url,configAttribute);
        });

        /**定义所有角色都可以访问的*/
        List<Role> allRoles = roleMapper.selectByExample(null);
        List<ConfigAttribute> configAttribute = getConfigAttribute(allRoles);
        configCacheMap.put("index",configAttribute);

        /**
         * 如果给login添加权限，那么自定义的拦截器就会拦截此方法，多此一举
         *
         * configCacheMap.put("/login",getDefault());
         * */


    }

    public static List<ConfigAttribute> get(String url) {
        return configCacheMap.get(url);
    }

    private static List<ConfigAttribute> getConfigAttribute(List<Role> urlRelationRoles) {
        List<ConfigAttribute> result = new ArrayList<>();
        ConfigAttribute attribute = new org.springframework.security.access.SecurityConfig("ROLE_BASE"); /** 将所有url都能让ROLE_BASE角色访问 */
        result.add(attribute);
        urlRelationRoles.forEach(role -> result.add(new org.springframework.security.access.SecurityConfig(role.getName())));
        return result;
    }

    private static List<ConfigAttribute> getDefault() {
        List<ConfigAttribute> result = new ArrayList<>();
        result.add(new SecurityConfig("ROLE_ANONYMOUS"));
        return result;
    }
}
